<template>
    <div class="article-edit">
        <div class="defaultBg">
            <div class="act-form-contant" v-bind:style="{ height: formHeight }">
                <el-form ref="actDetailData" :model="actDetailData" :rules="actDetailDataRules" label-width="120px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="活动名称：" prop="actTitle">
                                <el-input v-model="actDetailData.actTitle"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="活动类型：" prop="actType">
                                <el-radio-group v-model="actDetailData.actType" @input="actTypeChange" disabled>
                                    <el-radio :label="0">活动</el-radio>
                                    <el-radio :label="1">比赛</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="活动类型：" prop="signType">
                                <el-radio-group v-model="actDetailData.signType" disabled>
                                    <el-radio :label="0" :disabled="actDetailData.actType===1">扫码</el-radio>
                                    <el-radio :label="1" :disabled="actDetailData.actType===1">定位</el-radio>
                                    <el-radio :label="2" :disabled="actDetailData.actType===0">提交文件</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="20" v-if="actDetailData.actType===0 || scoreTypeIsReady">
                            <el-form-item label="活动加分：">
                                <el-checkbox-group v-model="scoreList" @change="scoreListChange" class="checkbox-g">
                                    <el-checkbox label="0" class="checkbox-i">
                                        创新分：
                                        <el-input v-model="chuangxinScore" :disabled="cInput" placeholder="请输入内容"></el-input>
                                    </el-checkbox>
                                    <el-checkbox label="1" class="checkbox-i">
                                        学业分：
                                        <el-input v-model="xueyeScore" :disabled="xInput" placeholder="请输入内容"></el-input>
                                    </el-checkbox>
                                    <el-checkbox label="2" class="checkbox-i">
                                        思想分：
                                        <el-input v-model="sixiangScore" :disabled="sInput" placeholder="请输入内容"></el-input>
                                    </el-checkbox>
                                    <el-checkbox label="3" class="checkbox-i">
                                        文体分：
                                        <el-input v-model="wentiScore" :disabled="wInput" placeholder="请输入内容"></el-input>
                                    </el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="20">
                            <el-form-item label="活动描述：" prop="actContent">
                                <quill-editor
                                    class="ql-editor"
                                    v-model="actDetailData.actContent"
                                    ref="myQuillEditor"
                                    :options="editorOption">
                                </quill-editor>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="活动创建人：" prop="organizerAccount">
                                <el-input v-model="actDetailData.organizerAccount" disabled style="width:220px;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="活动审批人：" prop="teacherAccount">
                                <el-select v-model="actDetailData.teacherAccount" placeholder="请选择审批人" style="width:220px;" disabled>
                                    <el-option
                                        v-for="item in teacherOptions"
                                        :key="item.id"
                                        :label="item.userName"
                                        :value="item.userAccount">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="活动开始时间：" prop="startTime">
                                <el-date-picker
                                    v-model="actDetailData.startTime"
                                    type="datetime"
                                    placeholder="选择活动开始时间">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="活动结束时间：" prop="endTime">
                                <el-date-picker
                                    v-model="actDetailData.endTime"
                                    type="datetime"
                                    placeholder="选择活动结束时间">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="20">
                            <el-form-item label="活动申请说明：" prop="applyDesc">
                                <el-input
                                    type="textarea"
                                    v-model="actDetailData.applyDesc"
                                    :rows="5"
                                    placeholder="请输入活动申请说明"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- <el-form-item label="活动图片：" prop="actImg">
                        <el-upload
                            class="upload-demo"
                            ref="actImgUpload"
                            :multiple="true"
                            :limit="9"
                            action="#"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :on-change="handleChange"
                            :file-list="fileList"
                            list-type="picture-card"
                            :auto-upload="false">
                            <i slot="default" class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-form-item> -->
                </el-form>
            </div>
        </div>

        <div class="bottom-button" ref="Button">
            <el-button icon="el-icon-document-checked" type="primary" size="small" @click="handleSubmit">提交</el-button>
            <el-button icon="el-icon-back" type="warning" size="small" @click="$router.push(`/article/articleList`)">返回</el-button>
        </div>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { getACTDetailInfo, getActScoreType, editACT } from '@/api/article'
import { getUserList } from '@/api/user'

import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
    name: 'article-edit',
    components: {
        quillEditor
    },
    computed: {
        ...mapGetters([
            'account',
        ])
    },
    data () {
        return {
            formHeight: '', // 表单自适应高度
            actDetailData: {
                actTitle: '',
                actType: 0,
                signType: 0,
                actContent: '',
                organizerAccount: '',
                teacherAccount: '',
                startTime: '',
                endTime: '',
                applyDesc: '',
            },
            actDetailDataRules: {
                actTitle: [
                    { required: true, message: '缺少活动名称', trigger: 'blur' }
                ],
                actType: [
                    { required: true, message: '请选择活动类型', trigger: 'blur' }
                ],
                signType: [
                    { required: true, message: '请选择签到类型', trigger: 'blur' }
                ],
                actContent: [
                    { required: true, message: '请填写活动描述', trigger: 'blur' }
                ],
                organizerAccount: [
                    { required: true, message: '请填入申办人名字', trigger: 'blur' }
                ],
                organizerAccount: [
                    { required: true, message: '请指定审批人', trigger: 'blur' }
                ],
                startTime: [
                    { required: true, message: '请选择活动开始时间', trigger: 'blur' }
                ],
                endTime: [
                    { required: true, message: '请选择活动结束时间', trigger: 'blur' }
                ],
                applyDesc: [],
            },
            teacherOptions: [],// 教师名单
            // 图片上传配置
            fileList: [],
            dialogImageUrl: '',
            dialogVisible: false,

            editorOption: {
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
                        [{ header: 1 }, { header: 2 }], // 1、2 级标题
                        [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
                        [{ script: 'sub' }, { script: 'super' }], // 上标/下标
                        [{ indent: '-1' }, { indent: '+1' }], // 缩进
                        [{ direction: 'rtl' }], // 文本方向
                        [{ header: [1, 2, 3, false] }], // 标题
                        [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
                        [{ align: [] }], // 对齐方式
                        ['clean'], // 清除文本格式
                    ]
                },
                placeholder: '请输入活动描述',
            },

            scoreList: [],
            chuangxinScore: 0.5,
            xueyeScore: 0.5,
            sixiangScore: 0.5,
            wentiScore: 0.5,
            cInput: true,
            xInput: true,
            sInput: true,
            wInput: true,
            scoreTypeIsReady: false,
            actId: this.$route.params.actId,
        }
    },
    methods: {
        async getActData () {
            const { data } = await getACTDetailInfo({ actId: this.actId })
            this.actDetailData = data
        },

        async getActScoreTypeFn () {
            const { data } = await getActScoreType({ actId: this.actId })
            data.forEach(item => {
                if (item.score_type == 0) {
                    this.cInput = false
                    this.scoreList.push('0')
                }
                else if (item.score_type == 1) {
                    this.xInput = false
                    this.scoreList.push('1')
                }
                else if (item.score_type == 2) {
                    this.sInput = false
                    this.scoreList.push('2')
                }
                else if (item.score_type == 3) {
                    this.wInput = false
                    this.scoreList.push('3')
                }
            })

            this.scoreTypeIsReady = true
        },

        // 获取教师（审批人）名单
        async getTeacherList () {
            const { data } = await getUserList({ role: 'teacher', limit: 100, offect: 1 })
            this.teacherOptions = data.resList
            this.actDetailData.organizerAccount = this.account
        },

        // 图片上传-删除图片
        handleRemove (file, fileList) {
            this.fileList = fileList
        },
        // 图片上传-上传图片
        handleChange (file, fileList) {
            this.fileList = fileList
        },
        // 图片上传-预览图片
        handlePreview (file) {
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },

        // 活动创建
        handleSubmit () {
            this.$refs.actDetailData.validate(async (valid) => {
                if (valid) {
                    // 提交编辑后的信息
                    let formata = new FormData()
                    for (const [key, value] of Object.entries(this.actDetailData)) {
                        formata.append(key, value)
                    }
                    // 活动加分类型
                    let signScoreList = []
                    if (!this.cInput) {
                        signScoreList.push({ scoreType: 0, score: this.chuangxinScore })
                    }
                    if (!this.xInput) {
                        signScoreList.push({ scoreType: 1, score: this.xueyeScore })
                    }
                    if (!this.sInput) {
                        signScoreList.push({ scoreType: 2, score: this.sixiangScore })
                    }
                    if (!this.wInput) {
                        signScoreList.push({ scoreType: 3, score: this.wentiScore })
                    }

                    if (signScoreList.length === 0 && this.actDetailData.signType !== 2) {
                        this.$message({
                            message: '请至少选择一个加分项',
                            type: 'error'
                        })
                        return
                    }

                    let hasZero = signScoreList.some((item) => item.score == '0')

                    if (hasZero) {
                        this.$message({
                            message: '分数不可为0',
                            type: 'error'
                        })
                        return
                    }

                    formata.append('signScoreList', JSON.stringify(signScoreList))

                    // this.fileList.map((file) => {
                    //     formata.append('actImg', file.raw)
                    // })
                    const res = await editACT(formata)
                    if (res.hasOk) {
                        this.$message({
                            message: '活动修改成功',
                            type: 'success'
                        })
                        // 跳转到活动申请列表
                        this.$router.push('/myArticle/myApplyList')
                    } else {
                        this.$message({
                            message: res.message,
                            type: 'error'
                        })
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },

        actTypeChange (value) {
            if (value === 0) {
                this.actDetailData.signType = 0
            } else if (value === 1) {
                this.actDetailData.signType = 2
            }
        },

        scoreListChange (value) {
            this.cInput = !value.some((item) => item === '0')
            this.xInput = !value.some((item) => item === '1')
            this.sInput = !value.some((item) => item === '2')
            this.wInput = !value.some((item) => item === '3')
            console.log(this.scoreList)
        },

        // 设置表单的自适应高度
        setFormHeight () {
            let fullHeight = document.body.clientHeight - this.$refs.Button.offsetHeight - 90
            this.formHeight = fullHeight > 300 ? fullHeight + 'px' : '300px'
            this.isHeightReady = true
        }
    },
    mounted () {
        this.setFormHeight()
        let that = this
        window.onresize = function temp () {
            that.setFormHeight()
        }
    },
    created () {
        this.getActData()
        this.getActScoreTypeFn()
    },
}
</script>

<style lang="scss" scoped>
.act-form-contant {
    width: 100%;
    height: 100%;
    padding: 20px 10px;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    overflow: auto;
}

.checkbox-g {
    .checkbox-i {
        margin-right: 100px;
    }
}

.bottom-button {
    position: absolute;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 50px;
    border-top: 1px solid #d9d9d9;
    background-color: #fff;
}
.quill-editor ::v-deep.ql-container {
    min-height: 220px;
}

.ql-container {
    min-height: 230px;
}
</style>